package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"github.com/tebeka/selenium"
)

var messagePubHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())

}

var connectHandler MQTT.OnConnectHandler = func(client MQTT.Client) {
	// 复制全局变量页面调用使用

	fmt.Println("Mqtt connect Connected")
	// 订阅主题
	client.Subscribe("script_web/go", 0, func(client MQTT.Client, message MQTT.Message) {
		// 存入redis还是直接赋值页面引用
		fmt.Printf("Received message: %s from topic: %s\n", message.Payload(), message.Topic())
		url := message.Payload()
		openAccountBrowser(string(url))
	})
}

var connectLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
	client.Connect()
	println("正在重新连接")
}

func mqttRun() {
	// 创建一个 MQTT 选项对象
	opts := MQTT.NewClientOptions()
	// opts.AddBroker("tcp://broker.emqx.io:1883")
	opts.AddBroker("tcp://39.104.71.213:1883")
	opts.SetClientID("go-mqtt-client")
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	// 创建一个 MQTT 客户端
	client := MQTT.NewClient(opts)
	// 连接到 MQTT 代理
	token := client.Connect()
	println("正在连接mqttBroker:", token)

}

func openAccountBrowser(url string) {
	fmt.Println(url)
	resp, _ := http.Get(url)
	body, _ := io.ReadAll(resp.Body)
	var result []map[string]any
	err := json.Unmarshal([]byte(string(body)), &result)
	if err != nil {
		fmt.Println("解析 JSON 错误：", err)
		return
	}

	_, _ = selenium.NewChromeDriverService("./chromedriver1.exe", 55555)
	caps := selenium.Capabilities{"browserName": "chrome"}
	wd, _ := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", 55555))
	_ = wd.DeleteAllCookies()
	_ = wd.Get("https://admin.yueyuechuxing.cn/login")
	// 等待页面加载
	time.Sleep(2 * time.Second)

	for _, v := range result {
		var myStruct selenium.Cookie
		myStruct.Name = v["name"].(string)
		myStruct.Value = v["value"].(string)
		myStruct.Path = v["path"].(string)
		myStruct.Domain = v["domain"].(string)
		myStruct.Secure = v["secure"].(bool)

		value, error1 := v["expiry"]
		num, ok := value.(float64)

		if error1 && ok {
			myStruct.Expiry = uint(num)
		} else {
			// 如果一直刷新页面，就改这个值，改成当前时间
			myStruct.Expiry = uint(time.Now().UnixNano()/1e9 + 30000000)
		}
		_ = wd.AddCookie(&myStruct)
	}
	_ = wd.Get("https://admin.yueyuechuxing.cn/ops/jointmarke/activitylist")

}

func openBrowser() {
	selenium.SetDebug(true)
	_, _ = selenium.NewChromeDriverService("./chromedriver1.exe", 4444)

	// defer service.Stop()

	// 创建一个 WebDriver 实例
	caps := selenium.Capabilities{"browserName": "chrome"}
	wd, _ := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", 4444))

	// defer wd.Quit()

	// 打开网页
	if err := wd.Get("http://192.168.31.122:5000/beike_account?password=123"); err != nil {
		panic(err)
	}
}

func main() {
	go mqttRun()
	go openBrowser()

	for {
		// time.Sleep(5 * time.Second)
	}

}
